package com.banksoft.admin.service.impl;

import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.dao.*;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.entity.UserAddress;
import com.banksoft.admin.entity.UserMoney;
import com.banksoft.admin.service.UserService;
import com.banksoft.front.bean.Page;
import com.banksoft.front.bean.UserBean;
import com.banksoft.util.StringNumber;
import com.banksoft.util.StringUtil;
import com.banksoft.util.UUIDFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by vanjoger on 2017/1/2.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    BaseMyBatisDao baseMyBatisDao;
    @Autowired
    UserMoneyDao userMoneyDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    UserAddressDao userAddressDao;

    public User findByOpenId(String openId) {
        return userDao.findByOpenId(openId);
    }

    @Override
    public List<User> findByAccount(String account) {
        return this.userDao.findByAccount(account);
    }

    @Override
    public void saveUser(User dto) {
        baseMyBatisDao.insert(UserDao.class,dto);
        List<UserMoney> moneys = userMoneyDao.findByUserId(dto.getId());

        if(!StringUtil.isNotEmpty(moneys)) {
            UserMoney money = new UserMoney();
            money.setId(UUIDFactory.random());
            money.setUserId(dto.getId());
            money.setUserName(dto.getNickName());
            money.setCash("0");
            money.setBonus("0");
            money.setFrozenAmount("0");
            money.setTotalAmount("0");
            this.baseMyBatisDao.insert(UserMoneyDao.class, money);
        }
    }

    @Override
    public List<User> listByName(String name) {
        return this.userDao.listByName(name);
    }

    @Override
    public void update(User user, String address) {
        if(user.getType().equals(MemberType.Partner.name())){//如果设置为区域代理人  则赠送给其对应的全国总代
            user.setType(MemberType.General.name());
            user.setIsPartner("1");
            user.setPartnerDate(new Date().getTime());
        }
        if(!user.getType().equals(MemberType.Customer.name())){
            User upuser = getUserUpper(user);
            if(upuser!=null)
                user.setRecommendId(upuser.getId());
        }
        user.setIsMember("1");
        this.baseMyBatisDao.update(UserDao.class,user);
        List<UserMoney> moneys = userMoneyDao.findByUserId(user.getId());
        UserMoney money = null;
        if(StringUtil.isNotEmpty(moneys))
            money = moneys.get(0);
        if(money==null){
            money = new UserMoney();
            money.setId(UUIDFactory.random());
            money.setUserId(user.getId());
            money.setUserName(user.getNickName());
            money.setCash("0");
            money.setBonus("0");
            money.setFrozenAmount("0");
            money.setTotalAmount("0");
            this.baseMyBatisDao.insert(UserMoneyDao.class,money);
        }
        List<UserAddress> userAddressList = this.userAddressDao.listByUserId(user.getId());
        if(StringUtil.isNotEmpty(userAddressList)){
            UserAddress userAddress = userAddressList.get(0);
            userAddress.setAddress(address);
            this.baseMyBatisDao.update(UserAddressDao.class,userAddress);
        }
    }

    /**
     * 将其上级为普通消费者的剔除
     * @param user
     */
    private User getUserUpper(User user) {
        if(!user.getRecommendId().equals(user.getId())) {
            User upUser = baseMyBatisDao.findById(UserDao.class, user.getRecommendId());
            if (upUser != null) {
                if (!upUser.getType().equals(MemberType.Customer.name())) {//不等于普通消费者的话
                    return upUser;
                } else {
                    return getUserUpper(upUser);
                }
            }
        }
        return null;
    }

    @Override
    public List<UserBean> listTeam(String id, boolean level) {
        List<User> list = this.userDao.listByRecommendId(id);
        if(level){
            User user = this.baseMyBatisDao.findById(UserDao.class,id);
            list.add(user);
        }
        List<UserBean> data = new ArrayList<>();
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                UserBean  bean = new UserBean();
                bean.setId(user.getId());
                bean.setNickName(user.getNickName());
                bean.setAccount(user.getAccount());
                bean.setHeadImgUrl(user.getHeadimgUrl());
                bean.setUserType(user.getType());
                if(MemberType.General.name().equals(user.getType())&&"1".equals(user.getIsPartner())){
                    bean.setUserType(MemberType.Partner.name());
                }
                List<UserAddress> addressList = this.userAddressDao.listByUserId(user.getId());
                if(StringUtil.isNotEmpty(addressList)){
                    UserAddress address = addressList.get(0);
                    bean.setRealName(address.getUserName());
                }

                List<User> userlist = this.userDao.listByRecommendId(user.getId());
                if(user.getId().equals(id)){//此处sql事务存在缓存  不执行查询数据 需要将数据-1
                    if(StringUtil.isNotEmpty(userlist)){
                        bean.setUserCnt(userlist.size()>0?userlist.size()-1:0);
                    }else{
                        bean.setUserCnt(0);
                    }
                }else {
                    bean.setUserCnt(userlist != null ? userlist.size() : 0);
                }

                String qyyj = "0";
                if(StringUtil.isNotEmpty(userlist)){
                    String ids = "";
                    for(User u:userlist){
                        ids += u.getId()+",";
                    }
                    if(ids.length()>0){
                        ids = ids.substring(0,ids.length()-1);
                    }
                    String[] arrays = ids.split(",");
                    List<Order> orderlist = this.orderDao.listByUserIds(arrays);
                    bean.setOrderCnt(orderlist!=null?orderlist.size():0);
                    if(StringUtil.isNotEmpty(orderlist)){
                        for(Order order:orderlist){
                            qyyj = StringNumber.add(order.getTotalMoney(),qyyj);
                        }
                    }
                }else{
                    bean.setOrderCnt(0);
                }
                bean.setQyyj(qyyj);
                data.add(bean);
            }
        }
        return data;
    }

    @Override
    public List<User> list(Map map) {
        return this.userDao.list(map);
    }

    @Override
    public List<User> listUserByCity(String userLevel, String province, String city, String area) {
        return this.userDao.listUserByCity(userLevel,province,city,area);
    }

    @Override
    public List<User> listPartnerUser() {
        return this.userDao.listPartnerUser();
    }

    @Override
    public List<User> listByRecommendId(String recommendId) {
        return this.userDao.listByRecommendId(recommendId);
    }

    @Override
    public Page queryPage(Map map, int pageNo, int pageSize) {
        Page page = new Page(pageNo,pageSize);
        map.put("start",page.getStart());
        map.put("size",pageSize);

        List<User> list = this.userDao.queryPage(map);
        Integer total = this.userDao.countPage(map);
        if(StringUtil.isNotEmpty(list)){
            for(User user:list){
                List<UserAddress> userAddressList = this.userAddressDao.listByUserId(user.getId());
                if(StringUtil.isNotEmpty(userAddressList)){
                    UserAddress userAddress = userAddressList.get(0);
                    if(!StringUtil.isNotNull(user.getCardName())){
                        user.setCardName(userAddress.getUserName());
                    }
                    if(!StringUtil.isNotNull(user.getMobile())){
                        user.setMobile(userAddress.getTelephone());
                    }
                    user.setUserAreaName(userAddress.getProvinceName()+userAddress.getCityName()+userAddress.getAreaName()+userAddress.getAddress());
                }
                //查找推荐人
                User upuser = this.baseMyBatisDao.findById(UserDao.class,user.getRecommendId());
                if(upuser!=null){
                    if(StringUtil.isNotNull(upuser.getCardName())){//真实姓名存在
                        user.setTdyj(upuser.getCardName());
                    }else{
                        List<UserAddress> upUserAddresses = this.userAddressDao.listByUserId(user.getRecommendId());
                        if(StringUtil.isNotEmpty(upUserAddresses)){//收货人存在
                            UserAddress address = upUserAddresses.get(0);
                            user.setTdyj(address.getUserName());
                        }else{//收货人不存在
                            user.setTdyj(upuser.getNickName()+"("+upuser.getAccount()+")");
                        }
                    }
                }
            }
        }
        page.setData(list);
        page.setTotal(total);
        return page;
    }

    @Override
    public Integer countPage(Map params) {
        return this.userDao.countPage(params);
    }

    @Override
    public List<User> searchByPage(Map params) {
        return this.userDao.queryPage(params);
    }


}
